﻿/////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Eric Bowen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, including 
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Author's blog: http://blog.scrappydog.com
// Updated source code available:  http://scrappydb.codeplex.com
/////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Linq;
using System.Web.Caching;
using ScrappyDB.BaseClasses;

namespace ScrappyDB.Utilities
{
    public static class LatLonProximity
    {
        public static SdbCollection<T> FindEnititiesByProximity<T>(double lat,
                                                                         double lon,
                                                                         double searchRadius,
                                                                         bool isMetric,
                                                                         Cache cache)
            where T : SdbEntityWithLocation, new()
        {
            var col = new SdbCollection<T>(cache);

            //returns all results in a square box of size 2 X searchRadius
            GetBoxResults(lat, lon, searchRadius, isMetric, col, cache);

            //now we need to get rid of any result in the corners that are outside the searchRadius
            RemoveCorners(lat, lon, searchRadius, col);

            return col;
        }

        public static void GetBoxResults<T>(double lat,
                                            double lon,
                                            double searchRadius,
                                            bool isMetric,
                                            SdbCollection<T> col, Cache cache) where T : SdbEntityWithLocation, new()
        {
            ProximityBox box = LatLonMath.CalculateProximity(lat, lon, searchRadius, isMetric);

            string maxLat = Utility.EncodeNumeric(box.LatMax);
            string minLat = Utility.EncodeNumeric(box.LatMin);
            string maxLon = Utility.EncodeNumeric(box.LonMax);
            string minLon = Utility.EncodeNumeric(box.LonMin);

            string query =
                String.Format(" Latitude > '{0}' and Latitude < '{1}' and Longitude > '{2}' and Longitude < '{3}' ",
                              minLat, maxLat, minLon, maxLon);

            col.QueryCollection(query,cache,true);
        }

        public static void RemoveCorners<T>(double lat, double lon, double searchRadius, SdbCollection<T> col)
            where T : SdbEntityWithLocation, new()
        {
            for (int i = col.Count() - 1; i >= 0; i--)
            {
                T loc = col[i];
                loc.Distance = LatLonMath.CalculateDistance(lat, lon, loc.Latitude, loc.Longitude, false);
                if (loc.Distance > searchRadius)
                    col.Remove(loc);
            }
        }
    }
}